#* -coding: utf - 8 -* -
"""
 Copyright 2010 Kruglov M.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

"""
import sys
import xmpp
import threading
from pyxmppbot import helpers,BasePeriodicTask,BaseXmppHandler,BaseKernelPlugin

class LogMessages(BaseXmppHandler):
    """Write incoming messages to main log file"""
    plugin_type = 'xmpp_handler'
    handler_type = 'message'
    makefirst = 1

    def onCall(self,conn,mess):
        if mess.getBody() != None:
            self.kern.logMessage(mess.getFrom().getStripped() + ": " + mess.getBody())

class Echo(BaseXmppHandler):
    """This plugin is very useful!"""

    plugin_type = 'xmpp_handler'
    handler_type = 'message'

    def onCall(self,conn,mess):
        if mess.getBody() != None:
            self.kern.sendMessage(mess.getFrom(),mess.getBody())

class AutoAuthorize(BaseXmppHandler):
    """Authorize, unauthorize user by request"""

    plugin_type = 'xmpp_handler'
    handler_type = 'presence'

    def afterPlug(self):
        xmpp.roster.Roster().PlugIn(self.kern.bot)
        self.kern.logMessage("xmpppy plugin 'roster' loaded")
        return True

    def onCall(self,conn,mess):
        type = mess.getType()
        if type == "subscribe":
            self.kern.logMessage("Auth request from %s. OK" % mess.getFrom().getStripped())
            self.kern.bot.Roster.Authorize(mess.getFrom().getStripped())
        elif type == "unsubscribe":
            self.kern.logMessage("User %s unauthorize me. OK" % mess.getFrom().getStripped())
            self.kern.bot.Roster.Unauthorize(mess.getFrom().getStripped())


class Uptime(BasePeriodicTask):

    timeout = 1
    def afterPlug(self):
        self.kern.sandbox.kernage = 0
        return True

    def onCall(self):
        self.kern.sandbox.kernage += 1

class ExecCommand(BaseXmppHandler):
    """
        Plugin, which can execute some commands.
        Commands, inside user classes, must be inherited
        from BaseCommand class (see examples). 
        
        Notice: 'print' in command class send 
        message to user, who requests command execute. 
    """

    plugin_type = 'xmpp_handler'
    handler_type = 'message'
    prefix = "./"
    authorized = list()
    passwd = "secret"
    commands = []
    threads = []

    class XmppOut(object):
        def __init__(self,send,rcpt):
            self.rcpt = rcpt
            self.send = send

        def write(self,text):
            if text != "\n":
                self.send(self.rcpt,text)

        def flush(self):
            pass

    class BaseCommand(object):
        enabled = False
        class Meta(type):

            def __init__(cls,*args):
                cls.name = cls.__name__

        __metaclass__ = Meta

        aliases = tuple()
        dependings = list()
        usage = ""
        authreq = False
        enabled = True

        def __call__(self,*args,**kwargs):
            oldout = sys.stdout
            sys.stdout = self.main.xmppout
            try:
                self.onCall(*args,**kwargs)
            except:
                self.main.logMessage.setTrace()

            sys.stdout = oldout

        def onCall(self,args,kwargs):
            pass

    class commandNotFound(BaseCommand):
        def onCall(self,*args,**kwargs):
            print "Command '%s' not found" % self.runas

    def addCommand(self,obj):
        self.kern.logMessage("adding command '%s'" % obj.name,0)
        name = 'child__' + obj.name
        self.sandbox.__setattr__(name,obj)
        self.sandbox.__getattribute__(name).main = self.sandbox
        self.sandbox.__getattribute__(name).logger = self.logger + '(' + obj.name + ')'

    def prePlug(self):
        self.sandbox = self.kern.sandbox
        return True

    def afterPlug(self):
        self.commands = self.updateCommandsList()
        self.sandbox.passwd = self.passwd
        self.sandbox.prefix = self.prefix
        self.sandbox.logMessage = self.kern.logMessage
        for each in self.commands:
            self.addCommand(each)

        for obj in self.sandbox:
            for dep in obj.dependings:
                if dep not in self.kern.loaded_plugins:
                    obj.enabled = False
                    self.kern.logMessage("command '%s' disabled, because it depends on the plugin '%s', but plugin '%s' not loaded!" % (obj.name,dep,dep),2)
        return True

    def preOnCall(self,conn,mess):
        if mess.getBody() != None:
            if mess.getBody().startswith(self.prefix):
                self.onCall(conn,mess)

    def onCall(self,conn,mess):
        sender = mess.getFrom()
        plen = len(self.prefix)
        self.message = mess.getBody()[plen:].strip()
        self.sandbox.sender = sender
        self.sandbox.xmppout = self.XmppOut(self.kern.sendMessage,sender)
        self.__runCommand(self.message)

    def __exe(self,obj,args):
        threading.Thread(target=obj,args=args).start()

    def __determine(self,text):
        text = text.split(' ')
        command = text[0]
        args = text[1:]
        objtorun = self.commandNotFound()
        for obj in self.sandbox:
            obj = obj()
            if obj.enabled:
                if command in obj.aliases or command == obj.name:
                    if obj.authreq:
                        if self.sender in self.authorized:
                            objtorun = obj
                            break
                    else:
                        objtorun = obj
                        break
        objtorun.runas = command
        return (objtorun,args)

    def __runCommand(self,text):
        obj,args = self.__determine(text)
        self.__exe(obj,args)

    def updateCommandsList(self):
        res = []
        for each in dir(self):
            each = eval('self.' + each)
            if hasattr(each,'enabled') and each.enabled:
                res.append(each)

        return res

